package com.admore.demo.reward;

import static com.admore.sdk.config.AdMoreConstants.AD_COUNT;
import static com.admore.sdk.config.AdMoreConstants.AD_HEIGHT;
import static com.admore.sdk.config.AdMoreConstants.AD_WIDTH;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.admore.demo.App;
import com.admore.demo.R;
import com.admore.demo.util.UIUtils;
import com.admore.sdk.ads.AdMoreRewardAd;
import com.admore.sdk.callback.AdMoreLoadListener;
import com.admore.sdk.callback.AdMoreMediaListener;
import com.admore.sdk.config.AdMoreConstants;
import com.admore.sdk.sdk.AdMoreSdk;
import com.zcy.base.ui.BaseActivity;

import java.util.HashMap;
import java.util.Set;

public class RewardActivity extends BaseActivity {

    private FrameLayout adMain;
    private boolean mLoadSuccess;
    private AdMoreRewardAd rewardAd;
    private long currentTimeMillis;

    @Override
    public int bindLayout() {
        return R.layout.activity_reward;
    }

    @Override
    public void initView() {
        adMain = findViewById(R.id.ad_main);
        ((TextView) findViewById(R.id.title)).setText("reward");
        ((TextView) findViewById(R.id.title)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (rewardAd == null) {
                    loadAd();
                } else {
                    if (rewardAd.isReady()) {
                        showAd();
                    } else {
                        rewardAd.loadAd(loadAdOptions("userid"));
                    }
                }
            }
        });
    }

    @Override
    public void initData() {

        loadAd();
    }

    private void loadAd() {
        if (!AdMoreSdk.init) {
            return;
        }
        Log.d(TAG, "start loadAd");
        currentTimeMillis = System.currentTimeMillis();
        if (!AdMoreSdk.init) {
            return;
        }
        if (rewardAd == null) {

            rewardAd = AdMoreSdk.getAdMoreSdkManager().createReward(this, App.AD_MORE_REWARD_ID, globalAdOptions());
            rewardAd.setLoadListener(new AdMoreLoadListener() {
                @Override
                public void onAdLoadSuccess(String msg) {
                    Log.d(TAG, "onAdLoadSuccess");
                    showAd();
                }

                @Override
                public void onAdLoadError(Throwable throwable) {
                    Log.d(TAG, "onAdLoadError" + throwable);
                }
            });
        }

        rewardAd.loadAd(loadAdOptions("userid"));
    }

    private HashMap<String, Object> globalAdOptions() {
        HashMap<String, Object> options = new HashMap<>();
        options.put(AD_WIDTH, adMain.getWidth());
        options.put(AD_HEIGHT, adMain.getHeight());
        options.put(AD_COUNT, 1);
        rewardAd = AdMoreSdk.getAdMoreSdkManager().createReward(this, App.AD_MORE_REWARD_ID, options);

        return options;
    }


    private HashMap<String, Object> loadAdOptions(String userId) {
        HashMap<String, Object> loadOptions = new HashMap<>();
        long r = System.currentTimeMillis();
        Log.i(TAG, "loadAdOptions: " + r);
        loadOptions.put(AdMoreConstants.CUSTOM_DATA_KEY_ADMORE_EXTRA, App.AD_MORE_APP_ID + "__gm__" + userId + "__" + r);
        loadOptions.put(AdMoreConstants.AD_MORE_CUSTOM_ADN_PANGLE, App.AD_MORE_APP_ID + "__csj__" + userId + "__" + r);
        loadOptions.put(AdMoreConstants.AD_MORE_CUSTOM_ADN_GDT, App.AD_MORE_APP_ID + "__gdt__" + userId + "__" + r);
        loadOptions.put(AdMoreConstants.AD_MORE_CUSTOM_ADN_KS, App.AD_MORE_APP_ID + "__ks__" + userId + "__" + r);
        loadOptions.put(AdMoreConstants.AD_MORE_CUSTOM_ADN_SIGMOB, App.AD_MORE_APP_ID + "__sigmob__" + userId + "__" + r);
        loadOptions.put(AdMoreConstants.AD_MORE_CUSTOM_ADN_BAIDU, App.AD_MORE_APP_ID + "__baidu__" + userId + "__" + r);

        return loadOptions;
    }

    private void showAd() {

        if (rewardAd.isReady()) {
            rewardAd.setMediaListener(new AdMoreMediaListener() {
                @Override
                public void onAdClosed() {
                    Log.d(TAG, "onAdClosed");
                }

                @Override
                public void onAdShow() {
                    Log.d(TAG, "onAdShow ecpm:" + rewardAd.getAdMoreInfo().getECPM() + " name:" + rewardAd.getAdMoreInfo().getSdkName());
                }

                @Override
                public void onAdPlayEnd() {
                    Log.d(TAG, "onAdPlayEnd");
                }

                /**
                 *
                 * @param isRewardValid 聚合平台验证状态(当聚合服务器未开启时此值为true)
                 * @param i
                 * @param extraInfo
                 */
                @Override
                public void onRewardArrived(boolean isRewardValid, int i, Bundle extraInfo) {
                    Log.d(TAG, "onRewardArrived isRewardV:" + isRewardValid + " i:" + i);

                    //以下代码必须聚合平台验证开启
                    boolean isServerSideVerify = extraInfo.getBoolean(AdMoreConstants.KEY_IS_ADMORE_SERVER_SIDE_VERIFY);
                    Log.d(TAG, "onRewardArrived isServerSideVerify:" + isServerSideVerify);
                    if (isServerSideVerify) {
                        // 开启了服务端激励验证，这里可以获取服务端激励验证信息
                        boolean isVerify = isRewardValid;
                        // 如果isVerify=false，则可以根据下面的错误码来判断为什么是false，
                        //  1、如果errorCode为40001/40002/50001/50002，则是因为请求异常导致，媒体可以根据自己的判断决定是否发放奖励。
                        //  2、否则，就是媒体服务端回传的验证结果是false，此时应该不发放奖励。

                        //打开注解查看所有返回的值
                        Set<String> strings = extraInfo.keySet();
                        for (String key : strings) {
                            Log.d(TAG, "->onRewardArrived，key:" + key + ",value:" + extraInfo.get(key));
                        }

                        Integer reason = (Integer) extraInfo.getInt(AdMoreConstants.KEY_REASON);
                        if (reason != null) {
                            Log.d(TAG, "onRewardArrived，开发者服务器回传的reason，开发者不传时为空");
                        }
                        Integer errorCode = (Integer) extraInfo.get(AdMoreConstants.KEY_ERROR_CODE);
                        if (errorCode != null) {
                            String errorMsg = (String) extraInfo.get(AdMoreConstants.KEY_ERROR_MSG);
                            Log.d(TAG, "onRewardArrived,服务端验证异常时的错误信息，未发生异常时为0或20000：errorCode:" + errorCode + ", errMsg: " + errorMsg);
                        }
                        String adExtra = (String) extraInfo.get(AdMoreConstants.KEY_ADMORE_EXTRA);
                        Log.d(TAG, "rewardItem, 开发者通过AdSlot传入的extra信息，会透传给媒体的服务器。开发者不传时为空，extra:" + adExtra);
                        String transId = (String) extraInfo.get(AdMoreConstants.KEY_TRANS_ID);
                        Log.d(TAG, "rewardItem, 服务端验证产生的transId，一次广告播放会产生的唯一的transid: " + transId);
                    }
                }
            });
            rewardAd.show(this, null);
        } else {
            Toast.makeText(getApplicationContext(), "请先加载广告", Toast.LENGTH_SHORT).show();
        }

    }
}
